using CanvasUI;
using DG.Tweening;
using KissEcs;
using level;
using Spine.Unity;
using System;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

public class Tutorial : Singleton<Tutorial>, IUI
{
    public Transform uiLayer;
    public Transform bubbleLayer;
    public bool isStart = false;
    GuideController guideController;
    public Canvas canvas;

    public GameObject empty;
    public Transform contentBar;

    public GameObject tip;
    public Button skipBtn;
    public Button skipMaskBtn;//点击结束弹窗的按钮
    public TMP_Text content;//弹窗文本
    public SkeletonGraphic finger;
    public bool isFollow = false;
    public event Action action;

    private Image bgMask;
    public bool canSkip = false;

    public bool isToturialLevel = false;

    public bool isPlayEndVideo = false;

    public bool needMask = true;

    protected override void Awake()
    {
        base.Awake();
        uiLayer = GameObject.Find("Canvas/UILayer").transform;
        bubbleLayer = GameObject.Find("Canvas/BubbleLayer").transform;
        canvas = GameObject.Find("Canvas").GetComponent<Canvas>();
        guideController = transform.GetComponent<GuideController>();

        bgMask = transform.GetComponent<Image>();
        tip.SetActive(false);
    }

    private void Start()
    {
        skipMaskBtn.onClick.AddListener(() =>
        {
            isStart = false;
            contentBar.gameObject.SetActive(false);
            skipMaskBtn.gameObject.SetActive(false);
            tip.SetActive(false);
            EventManager.Fire("CompleteStep", GuideMgr.Instance.stepIdx);
            EventManager.Fire("ResumeGame");
        });

        skipBtn.onClick.AddListener(() =>
        {
            isStart = false;
            contentBar.gameObject.SetActive(false);
            SkipSpecialInfo();
            GuideMgr.Instance.SkipGuide();
            finger.gameObject.SetActive(false);
        });

        contentBar.gameObject.SetActive(false);
        skipMaskBtn.gameObject.SetActive(false);
        finger.gameObject.SetActive(false);
        fingerPic.gameObject.SetActive(false);

        EventManager.Register("ExitGame", this, () =>
        {
            isPlayEndVideo = true;
        });
    }

    public void OnShow()
    {

    }

    public void OnHide()
    {

    }

    public void SkipSpecialInfo()
    {
        if (GuideMgr.Instance.guidingId == 5)
        {
            isFollow = false;
            action -= Temp5001;
        }
        if (GuideMgr.Instance.guidingId == 7)
        {
            uiLayer.Find("Main(Clone)/Ts/Text (TMP)").GetComponent<Button>().interactable = true;
        }
        if (GuideMgr.Instance.guidingId == 8)
        {
            isFollow = false;
            action -= Temp8001;
        }
    }

    public void Guide(RectTransform target, int type)
    {
        GuideType guideType = type == 1 ? GuideType.Circle : type == 0 ? GuideType.None : GuideType.Rect;
        guideController.Guide(canvas, target, guideType);
    }

    private void Update()
    {
        bgMask.enabled = isStart && needMask;
        skipBtn.gameObject.SetActive(canSkip && !GuideMgr.Instance.checkCondition);

        if (isFollow)
        {
            action.Invoke();
        }

    }

    private void StartMask(int idx, RectTransform rect)
    {
        Guide(rect, (int)GuideMgr.Instance.dict[idx].parameter);
    }

    #region 分步骤方法逻辑
    public void InitLogicAdd(int id)
    {
        switch (id)
        {
            default:
                break;
        }
    }


    public void HookBtnClick(Button btn, Action callback)
    {
        var oldOnClick = btn.onClick;
        btn.onClick = new();
        btn.onClick.AddListener(() =>
        {
            if (GuideMgr.Instance.guidingId > 4)
            {
                DOTween.KillAll();
            }
            oldOnClick.Invoke();
            if (btn != null && oldOnClick != null)
            {
                btn.onClick.RemoveAllListeners();
                btn.onClick.AddListener(() =>
                {
                    oldOnClick.Invoke();
                });
            }

            //btn.onClick = oldOnClick;
            callback();
        });
    }

    private void StartMaskAndGuide(RectTransform rect, int id)
    {
        ClickAnim(true, rect.position);
        StartMask(id, rect);
    }

    private void StartMaskAndGuide(RectTransform rect, int id, Vector3 pos)
    {
        ClickAnim(true, pos);
        StartMask(id, rect);
    }

    private void ClickCompleteStep(Button btn, int idx, Action action = null)
    {
        HookBtnClick(btn, () =>
        {
            if (action != null)
            {
                action.Invoke();
            }
            ClickAnim(false);
            isStart = false;
            canSkip = false;
            EventManager.Fire("CompleteStep", idx);
        });
    }

    private void ClickAnim(bool state, Vector3 pos = new())
    {
        if (state && pos != null)
        {
            finger.transform.position = pos;
        }
        finger.gameObject.SetActive(state);

    }

    #region 条件判断
    public bool ComputeCondition(int idx)
    {
        bool state = false;
        GameObject obj, last;
        switch (idx)
        {
            case 0:
                obj = GameObject.Find("Canvas/UILayer/Main(Clone)");
                state = CheckCanvas(obj);
                break;
            default:
                break;
        }

        return state;
    }

    public bool CheckCanvas(GameObject obj)
    {
        bool active = false;
        //若处于恢复游戏弹框时不通过加载请求
        var recover = GameObject.Find("Canvas/UILayer/RecoverGameUI(Clone)");
        //var bar = GameObject.Find("Canvas/UILayer/Bar(Clone)");
        if (recover != null)
        {
            var group = recover.GetComponent<CanvasGroup>();
            if (group.alpha == 1)
            {
                return false;
            }
        }

        if (obj != null)
        {
            var group = obj.GetComponent<CanvasGroup>();
            active = group.alpha == 1;
        }

        return active;
    }

    public bool CheckExp()
    {
        Transform rect = GetExp();
        return rect != null;
    }

    public void ChangeTextBarPos(string posName)
    {
        var pos = transform.Find($"PosBar/{posName}").position;
        contentBar.transform.position = pos;
        contentBar.gameObject.SetActive(true);
    }

    /// <summary>
    /// 检测是否场景中有经验球掉落
    /// </summary>
    public Transform GetExp()
    {
        var content = GameObject.Find("GameBoard/ExpLayer").transform;
        Transform rect = null;
        for (int i = 0; i < content.childCount; i++)
        {
            if (content.GetChild(i).name == "exp_green_s(Clone)")
            {
                rect = content.GetChild(i);
                break;
            }
        }
        return rect;
    }


    #endregion

    #endregion

}
